package com.ship.file.service;

import com.ship.common.core.utils.HttpUtils;
import com.ship.common.core.utils.file.FileUtils;
import com.ship.system.api.domain.SysFile;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.ship.file.utils.FileUploadUtils;

/**
 * 本地文件存储
 * 
 * @author zhangyh
 */
@Primary
@Service
public class LocalSysFileServiceImpl implements ISysFileService
{
    /**
     * 资源映射路径 前缀
     */
    @Value("${file.prefix}")
    public String localFilePrefix;

    /**
     * 域名或本机访问地址
     */
    @Value("${file.http-domain}")
    public String httpDomain;

    /**
     * 域名或本机访问地址
     */
    @Value("${file.https-domain}")
    public String httpsDomain;
    
    /**
     * 上传文件存储在本地的根路径
     */
    @Value("${file.path}")
    private String localFilePath;

    /**
     * 本地文件上传接口
     * 
     * @param file 上传的文件
     * @return 访问地址
     * @throws Exception
     */
    @Override
    public SysFile uploadFile(MultipartFile file) throws Exception
    {
        String name = FileUploadUtils.upload(localFilePath, file);
        name = HttpUtils.encodeChineseInUrl(name);
        String httpUrl = httpDomain + localFilePrefix + name;
        String httpsUrl = httpsDomain + localFilePrefix + name;
        httpUrl = httpUrl.replace(" ", "%20");
        httpsUrl = httpsUrl.replace(" ", "%20");
        SysFile sysFile = new SysFile();
        sysFile.setName(FileUtils.getName(httpDomain));
        sysFile.setHttpUrl(httpUrl);
        sysFile.setHttpsUrl(httpsUrl);
        return sysFile;
    }
}
